//
//  ApiSync.swift
//  YOKO
//
//  Created by 鲁浩 on 16/5/19.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON

class ApiSync {

	let DEBUG_TAG = "APISync"

	let MESSAGE_DATA = "data"
	let MESSAGE_MESSAGE = "msg"
	let MESSAGE_RESULT = "result"
	let MESSAGE_STATUS = "status"

	let MESSAGE_SYSTEM_CALENDAR_ERROR_CODE = -10086;

	// calendarEntry
	let CALENDARENTRY_CALENDARID = "calendar_id"
	let CALENDARENTRY_CALENDARENRTY = "calendarEntry"

	let CALENDARENTRY_UUID = "uuid"
	let CALENDARENTRY_VERSION = "version"
	let CALENDARENTRY_ETAG = "etag"
	let CALENDARENTRY_UPDATETIME = "updateTime"
	let CALENDARENTRY_CREATETIME = "createTime"
	let CALENDARENTRY_SUMMARY = "summary"
	let CALENDARENTRY_DESCRIPTION = "description"
	let CALENDARENTRY_LOCATION = "location"
	let CALENDARENTRY_TIMEZONE = "timezone"
	let CALENDARENTRY_SUMMARYOVERRIDE = "summaryOverride"
	let CALENDARENTRY_COLOR = "color"
	let CALENDARENTRY_HIDDEN = "hidden"
	let CALENDARENTRY_SELECTED = "selected"
	let CALENDARENTRY_ACCESSROLE = "accessRole"
	let CALENDARENTRY_DEFAULTREMINDERS = "defaultReminders"
	let CALENDARENTRY_NOTIFICATIONSETTINGS = "notificationSettings"
	let CALENDARENTRY_CATEGORY = "category"
	let CALENDARENTRY_SOURCE = "source"
	let CALENDARENTRY_ISPRIMARY = "primary"
	let CALENDARENTRY_DELETED = "deleted"

	// event
	let EVENT_UUID = "uuid"
	let EVENT_VERSION = "version"
	let EVENT_ETAG = "etag"
	let EVENT_STATUS = "status"
	let EVENT_SUMMARY = "summary"
	let EVENT_HTML = "htmlLink"
	let EVENT_UPDATETIME = "updateTime"
	let EVENT_CREATETIME = "createTime"
	let EVENT_TIMEZONE = "timeZone"
	let EVENT_TIME_BEGIN = "timeBegin"
	let EVENT_TIME_END = "timeEnd"
	let EVENT_REPEATRULE = "repeatRULE"
	let EVENT_REPEATEXRULE = "repeatEXRULE"
	let EVENT_REPEATRDATE = "repeatRDate"
	let EVENT_REPEATEXDATE = "repeatExDate"
	let EVENT_TRANSPARENCY = "transparency"
	let EVENT_VISIBILITY = "visibility"
	let EVENT_ICALUID = "icalUid"
	let EVENT_SEQUENCE = "sequence"
	let EVENT_ANYONECANADDSELF = "anyoneCanAddSelf"
	let EVENT_GUESTCANINVITEOTHERS = "guestCanInviteOthers"
	let EVENT_GUESTCANMODIFY = "guestCanModify"
	let EVENT_GUESTCANSEEOTHERGUESTS = "guestCanSeeOtherGuests"
	let EVENT_PRIVATECOPY = "privateCopy"
	let EVENT_LOCKED = "locked"
	let EVENT_REMINDER = "reminders"
	let EVENT_TYPE = "type"
	let EVENT_PROPERTY = "property"
	let EVENT_LOCATION = "location"
	let EVENT_DESCRIPTION = "description"
	let EVENT_ISWHOLEDAYEVENT = "wholeDayEvent"
	let EVENT_COLOR = "color"
	let EVENT_DELETED = "deleted"

	// sync
	let SYNC_TASK_TOKEN = "sync_token"

	let SYNC_TASK_CALENDAR = "calendar"
	let SYNC_TASK_EVENT = "event"

	let SYNC_TASK_VERSION = "version"
	let SYNC_TASK_DOWNLOAD = "download"
	let SYNC_TASK_UUID = "id"

    func updateCalendarToServiceSync(calendarEntry: Calendar, isAdd: Bool, callback: (NSDictionary?, NSError?) -> ()) {
        if (NSUserDefaults.getAccessToken() == nil) {
            return
        }
		let uuid = calendarEntry.uuid
		let params = UrlBuilder()
		if (uuid != "" && !isAdd) {
			params.appendParam(CALENDARENTRY_UUID, value: uuid)
		}
		params.appendParam(CALENDARENTRY_SUMMARY, value: calendarEntry.summary);
		params.appendParam(CALENDARENTRY_ETAG, value: calendarEntry.etag);
		params.appendParam(CALENDARENTRY_CREATETIME, value: NSDate.getTimeStamp(calendarEntry.createTime));
		params.appendParam(CALENDARENTRY_UPDATETIME, value: NSDate.getTimeStamp(calendarEntry.updateTime));
		params.appendParam(CALENDARENTRY_DESCRIPTION, value: calendarEntry.descriptions);
		params.appendParam(CALENDARENTRY_LOCATION, value: calendarEntry.location);
		params.appendParam(CALENDARENTRY_TIMEZONE, value: calendarEntry.timezone);
		params.appendParam(CALENDARENTRY_SUMMARYOVERRIDE, value: calendarEntry.summaryOverride);
		params.appendParam(CALENDARENTRY_COLOR, value: calendarEntry.color);
		params.appendParam(CALENDARENTRY_HIDDEN, value: calendarEntry.hidden);
		params.appendParam(CALENDARENTRY_SELECTED, value: calendarEntry.selected);
		params.appendParam(CALENDARENTRY_ACCESSROLE, value: calendarEntry.accessRole);
		params.appendParam(CALENDARENTRY_DEFAULTREMINDERS, value: calendarEntry.defaultReminders);
		params.appendParam(CALENDARENTRY_NOTIFICATIONSETTINGS, value: calendarEntry.notificationSettings);
		params.appendParam(CALENDARENTRY_ISPRIMARY, value: calendarEntry.primary);
		params.appendParam(CALENDARENTRY_DELETED, value: calendarEntry.deleted);
		params.appendParam(CALENDARENTRY_VERSION, value: calendarEntry.version);
        params.appendParam(CALENDARENTRY_CATEGORY, value: calendarEntry.category);
        params.appendParam(CALENDARENTRY_SOURCE, value: calendarEntry.source);
		if (isAdd) {
            Alamofire.request(.POST, URL_SYNC_ADD_CALENDAR, parameters: params.build(), encoding: .JSON)
                .responseJSON { response in
                    switch response.result {
                    case .Success(let value):
                        callback(value as? NSDictionary, nil)
                    case .Failure(let error):
                        callback(nil, error)
                    }
            }
		} else {
            Alamofire.request(.POST, URL_SYNC_UPDATE_CALENDAR, parameters: params.build(), encoding: .JSON)
                .responseJSON { response in
                    switch response.result {
                    case .Success(let value):
                        callback(value as? NSDictionary, nil)
                    case .Failure(let error):
                        callback(nil, error)
                    }
            }
		}
	}

    
//    NSUserDefaults.standardUserDefaults().setObject("3815ef71-e162-4efb-901c-136bb287df1a", forKey: "access_token")
//    NSUserDefaults.standardUserDefaults().setObject("d0648d9f-4cbb-491c-b363-a3db29a9c5b8", forKey: "calendar_uuid")
//    let c = Event()
//    let api = ApiSync()
//    api.updateEventToService(c, isAdd: true)
    
    func updateEventToService(eventEntry: Event, isAdd: Bool, calendarId: String, callback: (NSDictionary?, NSError?) -> ()) {
        if (NSUserDefaults.getAccessToken() == nil) {
            return
        }
 		let uuid = eventEntry.uuid;
		let params = UrlBuilder()
		if (uuid != "" && !isAdd) {
			params.appendParam(EVENT_UUID, value: uuid);
		}
		params.appendParam(EVENT_SUMMARY, value: eventEntry.summary);
		params.appendParam(EVENT_ETAG, value: eventEntry.etag);
		params.appendParam(EVENT_CREATETIME, value: NSDate.getTimeStamp(eventEntry.createTime));
		params.appendParam(EVENT_UPDATETIME, value: NSDate.getTimeStamp(eventEntry.updateTime));
		params.appendParam(EVENT_DESCRIPTION, value: eventEntry.descriptions);
		params.appendParam(EVENT_REMINDER, value: eventEntry.reminders);
		params.appendParam(EVENT_TYPE, value: eventEntry.type);
		params.appendParam(EVENT_LOCATION, value: eventEntry.location);
		params.appendParam(EVENT_ICALUID, value: eventEntry.icalUid);
		params.appendParam(EVENT_STATUS, value: eventEntry.status);
		params.appendParam(EVENT_HTML, value: eventEntry.htmlLink);
		params.appendParam(EVENT_TIMEZONE, value: eventEntry.timezone);
		params.appendParam(EVENT_TRANSPARENCY, value: eventEntry.transparency);
		params.appendParam(EVENT_VISIBILITY, value: eventEntry.visibility);
		params.appendParam(EVENT_REPEATRULE, value: eventEntry.repeatRULR);
		params.appendParam(EVENT_REPEATEXRULE, value: eventEntry.repeatEXRULE);
		params.appendParam(EVENT_SEQUENCE, value: eventEntry.sequence);
		params.appendParam(EVENT_ANYONECANADDSELF, value: eventEntry.anyoneCanAddSelf);
		params.appendParam(EVENT_GUESTCANINVITEOTHERS, value: eventEntry.guestCanInviteOthers);
		params.appendParam(EVENT_GUESTCANMODIFY, value: eventEntry.guestCanModify);
		params.appendParam(EVENT_GUESTCANSEEOTHERGUESTS, value: eventEntry.guestCanSeeOtherGuests);
		params.appendParam(EVENT_PRIVATECOPY, value: eventEntry.privateCopy);
		params.appendParam(EVENT_LOCKED, value: eventEntry.locked);
		params.appendParam(EVENT_DELETED, value: eventEntry.deleted);
		params.appendParam(EVENT_PROPERTY, value: eventEntry.property);
		params.appendParam(EVENT_TIME_BEGIN, value: NSDate.getTimeStamp(eventEntry.timeBegin));
		params.appendParam(EVENT_TIME_END, value: NSDate.getTimeStamp(eventEntry.timeEnd));
		params.appendParam(EVENT_ISWHOLEDAYEVENT, value: eventEntry.wholeDayEvent);
		params.appendParam(EVENT_REPEATEXDATE, value: eventEntry.repeatExDate);
		params.appendParam(EVENT_REPEATRDATE, value: eventEntry.repeatRDate);
		params.appendParam(EVENT_COLOR, value: eventEntry.color);
		params.appendParam(EVENT_VERSION, value: eventEntry.version);
		if (isAdd) {
            Alamofire.request(.POST, URL_SYNC_ADD_EVENT(calendarId), parameters: params.build(), encoding: .JSON)
                .responseJSON { response in
                    switch response.result {
                    case .Success(let value):
                        callback(value as? NSDictionary, nil)
                    case .Failure(let error):
                        callback(nil, error)
                    }
            }
		} else {
            NSLog("URL_SYNC_UPDATE_EVENT == " +  URL_SYNC_UPDATE_EVENT())
            Alamofire.request(.POST, URL_SYNC_UPDATE_EVENT(), parameters: params.build(), encoding: .JSON)
                .responseJSON { response in
                    switch response.result {
                    case .Success(let value):
                        callback(value as? NSDictionary, nil)
                    case .Failure(let error):
                        callback(nil, error)
                    }
            }
		}
	}

	// todo: 处理结果
    func pullCalendarList(callback: (JSON?, NSError?) -> ()) {
		let params = UrlBuilder()
//		params.appendSyncToken()
//		params.appendAccessToken()
        print("pull URL: ")
        print(URL_SYNC_PULL)
		Alamofire.request(.GET, URL_SYNC_PULL, parameters: params.build())
			.responseJSON { response in
                switch response.result {
                case .Success(let value):
                    callback(JSON(value), nil)
                case .Failure(let error):
                    callback(nil, error)
                }
		}
	}

}